/**
 * class pineapple.Memory
 *
 * March 28, 2012 
 * @authors Roman Kotusev, Darjuš Ilcevič, Kristis Vaškys
 */

/* 
 * Klasė, kuri imituoja realios masinos atmintį. 
 * Atmintis - vienmatis "Integer" tipo masyvas. 
 * 
 */
package pineapple;

public class Memory {

    private static final int SIZE = 768;
    
    private Integer[] RAM;

    /*Konstruktorius*/
    Memory() {
        RAM = new Integer[SIZE];
    }
    /*Metodai*/

    public void setNumber(Integer value, Integer address) {
        RAM[address] = value;
    }

    public Integer getNumber(Integer address) {
        return RAM[address];
    }

    public void setWord(String word, Integer address) {
        char[] values = word.toCharArray();

        byte[] numbers = new byte[4];
        for (int i = 0; i < word.length(); i++) {
            numbers[i] = (byte) values[i];
        }
        for (int i = word.length(); i < 4; i++) {
            numbers[i] = 0;
        }

        RAM[address] = numbers[3] + numbers[2] * 256 + numbers[1] * 256 * 256 
                        + numbers[0] * 256 * 256 * 256;
    }

    public String getWord(Integer address) {
        String word = "";               // output String
        byte[] numbers = new byte[4];
        Integer number = RAM[address];
        
        if (number == null) {
            return null;                // return if empty 
        }
        numbers[3] = (byte) (number % 256);                 // get fourth symbol
        numbers[2] = (byte) ((number / 256) % 256);         // get third symbol
        numbers[1] = (byte) ((number / 256 / 256) % 256);   // get second symbol
        numbers[0] = (byte) (number / 256 / 256 / 256);     // get first symbol
        for (int i = 0; i < 4; i++) {
            if ((numbers[i] < 32) || (numbers[i] > 126)) {
                numbers[i] = 32;
            }
        }
        word += "" + (char) numbers[0] + (char) numbers[1] 
                  + (char) numbers[2] + (char) numbers[3];
        return word;
    }

    public int getSize() {
        return SIZE;
    }

    public void printRam() {
        for (int i = 0; i < RAM.length - 1; i++) {
            if (RAM[i] != null) {
                System.out.println("RAM[" + i + "]: "
                                    + RAM[i] + " " + getWord(i));
            }
        }
    }

    @Override
    public String toString() {
        String mem = getWord(0);
        
        for (int i = 1; i < SIZE; i++) {
            mem += ":" + getWord(i);
        }
        return mem;
    }
}
